from math import floor
import subprocess
import os


class ApkInfo:
    """
    获取 apk 包 相关信息
    """
    def __init__(self, apk_path):
        self.apk_path = apk_path

    # 得到app的文件大小
    def get_apk_size(self):
        size = floor(os.path.getsize(self.apk_path) / (1024 * 1000))
        return str(size) + "M"

    # 得到版本
    def get_apk_version(self):
        cmd = " aapt dump badging " + self.apk_path + " | grep versionName"
        p = subprocess.Popen(cmd, stdout=subprocess.PIPE,
                             stderr=subprocess.PIPE,
                             stdin=subprocess.PIPE, shell=True)
        (output, err) = p.communicate()
        if output != "":
            result = output.split()[3].decode()[12:]
        return result

    # 得到应用名字
    def get_apk_name(self):
        cmd = "aapt dump badging " + self.apk_path + " | grep application-label-en"
        result = ""
        p = subprocess.Popen(cmd, stdout=subprocess.PIPE,
                             stderr=subprocess.PIPE,
                             stdin=subprocess.PIPE, shell=True)
        (output, err) = p.communicate()
        if output != "":
            result = output.split()[0].decode()[21:]
        return result

    # 得到包名
    def get_apk_pkg(self):
        cmd = "aapt dump badging " + self.apk_path + " | grep package:"
        result = ""
        p = subprocess.Popen(cmd, stdout=subprocess.PIPE,
                             stderr=subprocess.PIPE,
                             stdin=subprocess.PIPE, shell=True)
        (output, err) = p.communicate()
        if output != "":
            result = output.split()[1].decode()[6:-1]
        return result

    # 得到启动类
    def get_apk_activity(self):
        cmd = "aapt dump badging " + self.apk_path + " | grep launchable-activity:"
        result = ""
        p = subprocess.Popen(cmd, stdout=subprocess.PIPE,
                             stderr=subprocess.PIPE,
                             stdin=subprocess.PIPE, shell=True)
        (output, err) = p.communicate()
        if output != "":
            result = output.split()[1].decode()[6:-1]
        return result


if __name__ == '__main__':
    pass
    # apk_path = '/Users/david/Desktop/config/AREX_Debug_2.4.7.apk'
    # size = ApkInfo(apk_path).get_apk_size()
    # print(size)
    # ver = ApkInfo(apk_path).get_apk_version()
    # print(ver)
    # name = ApkInfo(apk_path).get_apk_name()
    # print(name)
    # pkg = ApkInfo(apk_path).get_apk_pkg()
    # print(pkg)
    # avtivity = ApkInfo(apk_path).get_apk_activity()
    # print(avtivity)
